<?php
namespace Biz\validate\activity;

use Doraemon\pockets\validate\Base;
use Biz\service\Sku;
use Biz\service\Goods;
use Biz\service\activity\AllActivityInfo;
use function GuzzleHttp\Promise\all;
use Biz\service\activity\AllactivityInfoBak;


class GroupBuy extends Base
{
	public static function rules()
	{
		return [

			['start_time', 'required', null, '请选择开始时间',['common']],

			['end_time', 'required', null, '请选择结束时间',['common']],

			['end_time', 'Callback',['callback' => [new self(), 'checkTimer']], '时间范围选择有误',['common']],

			['goods_id', 'required', null, '请选择商品id',['common']],
			['goods_id', 'Callback', ['callback' => [new self(), 'checkGoodsActivitesTime']], '相同时间内商品存在其他活动， 请规划好时间范围',['common']],

			['min_count', 'required', null, '请选择成团门槛',['common']],
			['min_count', 'GreaterThan', ['min' => 1, 'inclusive' => FALSE], '门槛数必须大于1',['common']],

			['group_buy_price', 'Callback', ['callback' => [new self(), 'checkSkusIsEmpty']], '请至少选择一个sku',['common']],
			['group_buy_price', 'Callback', ['callback' => [new self(), 'checkSkusPrice']], '请检查sku价格是否设置完全或存在大于原始价格的sku',['common']],
		];
	}

	public function checkGoodsActivitesTime($value, $valueChecker, $allData) {
        list($goodsIds, $invalidData) = AllactivityInfoBak::admCheckActivityTime(
            [$allData['goods_id']],
            ['start_time' => $allData['start_time'], 'end_time' => $allData['end_time']],
            AllactivityInfoBak::ACTIVITY_TYPE_TUAN,
            $allData['groupbuy_id']
        );

		if($invalidData) {
			if(isset($allData['groupbuy_id']) && $allData['groupbuy_id']) foreach ($invalidData as $invalidDatum) { //编辑状态
				if ($invalidDatum['type'] != AllActivityInfo::ACTIVITY_TYPE_TUAN && $invalidDatum['activity_id'] != $allData['groupbuy_id']) {
					return false;
				}
			} else { //添加状态
				return false;
			}
		}
		return true;
	}

	public function  checkTimer($value, $valueChecker, $allData) {
		if ($allData['end_time'] < $allData['start_time']) {
			return false;
		}
		return true;
	}

	public function checkSkusIsEmpty($value, $valueChecker, $allData) {
		if (! array_filter($allData['group_buy_price'])) {
			return false;
		}
		return true;
	}

	public function checkSkusPrice($value, $valueChecker, $allData) {
		$skuInfo = Sku::Sku([$allData['goods_id']], Sku::FIELDS_GROUP_SKU_INFO)[$allData['goods_id']];
		foreach ($skuInfo as  $item) {
			if (!isset($allData['group_buy_price'][$item['sku_id']]) || !$allData['group_buy_price'][$item['sku_id']] || $allData['group_buy_price'][$item['sku_id']] > $item['ori_price']) {
				return false;
			}
		}

		return true;
	}
}